package com.wjk.cms.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wjk.cms.common.Result;
import com.wjk.cms.pojo.Category;
import com.wjk.cms.pojo.Message;
import com.wjk.cms.pojo.User;
import com.wjk.cms.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/message")
public class MessageController extends AuthenticatedController {

    @Autowired
    private MessageService messageService;







    @PostMapping("/list")
    public Result list(
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, // 页码
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize
    ) {
        User currentUser = getCurrentUser();
        if(!currentUser.getType().equals("2")){
            return Result.error("非经销商没有权限操作");
        }
        List<Message> list =messageService.list(currentUser.getId(),status,pageNo,pageSize);
        return Result.ok().add("data", list);
    }



    @PostMapping("/detail")
    public Result detail(
            @RequestParam(value = "id", required = true) Long id
    ) {
        User currentUser = getCurrentUser();

        Message message = messageService.getById(id);
        return Result.ok().add("message", message);
    }

    @PostMapping("/add")
    public Result add(
            Message message
    ) {
        String detail = message.getDetail();
        List<Category> categories = JSON.parseArray(detail, Category.class);
        String str = "";
        String info = "";
        for (Category category : categories) {
            if(category.getNum()!=null && category.getNum()>0){
                str += category.getId()+":"+category.getNum()+",";
                info += category.getName()+"("+category.getSpec()+"),"+category.getNum()+"张;";
            }
        }
        User currentUser = getCurrentUser();
        message.setUserId(currentUser.getId());
        message.setStatus(0);
        message.setDetail(str.substring(0,str.lastIndexOf(",")));
        message.setInfo(info);
        messageService.save(message);
        return Result.ok().add("message", message);
    }




}
